<template>
    <el-container class="data_auth_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <el-select v-model="searchForm.application" v-if="appList.length > 1"
                                   @change="getList(true)" style="width: 150px;">
                            <el-option v-for="(item, index) in appList" :key="index"
                                       :label="item.name" :value="item.code" />
                        </el-select>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent"/>
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import {mapState} from "vuex";

export default {
    name: "DataAuth",
    props: {
        type: {
            type: String,
            default: 'row',
        },
    },
    data() {
        const _this = this;
        return {
            searchForm: {},
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                ],
                toolbar_filter: [],
            },
            dataList: [],
            tableOptions: {
                ref: `${_this.type}SysDataAuthTable`,
                container: '.data_auth_container',
                columns: [],
                baseColumns: [
                    {
                        label: "所属模块",
                        prop: "application",
                        align: "center",
                        permission: ['row', 'field'],
                        formatter(row) {
                            let filter = _this.appList.filter(item => item.code === row.application);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                return filter[0].name;
                            }
                            return '';
                        },
                    },
                    {
                        label: "功能编码",
                        prop: "code",
                        align: "center",
                        permission: ['row', 'field'],
                    },
                    {
                        label: "功能名称",
                        prop: "name",
                        align: "center",
                        permission: ['row', 'field'],
                    },
                    {
                        label: "是否启用范围权限",
                        prop: "need_auth",
                        align: "center",
                        permission: ['row'],
                        cellRender: {
                            name: 'ElSwitch',
                            props: {
                                activeValue: 1,
                                inactiveValue: 0,
                            },
                            events: {
                                change: _this.saveRow,
                            },
                        },
                    },
                    {
                        label: "是否启用字段权限",
                        prop: "need_auth",
                        align: "center",
                        permission: ['field'],
                        cellRender: {
                            name: 'ElSwitch',
                            props: {
                                activeValue: 1,
                                inactiveValue: 0,
                            },
                            events: {
                                change: _this.saveRow,
                            },
                        },
                    },
                    {
                        label: "授权字段",
                        prop: "auth_field_list",
                        align: "center",
                        permission: ['field'],
                        editRender: {
                            name: 'CustomSelect',
                            props: {
                                multiple: true,
                                filterable: true,
                                dataMethod(row) {
                                    let list =  _this.paramsList.filter(item => item.key2 === row.sid);
                                    return list.map(item => {
                                        return {
                                            label: item.display_text,
                                            value: item.value,
                                        };
                                    });
                                },
                            },
                            events: {
                                change: _this.saveRow,
                            },
                        },
                        formatter(row) {
                            let filter = _this.paramsList.filter(item => item.key2 === row.sid && row.auth_field_list.indexOf(item.value) !== -1);
                            return filter.map(item => item.display_text).join('、');
                        },
                    },
                ],
                pagination: {
                    pageIndex: 1,
                    pageSize: window.configs.pageSize,
                },
            },
            paramsList: [],
        };
    },
    computed: {
        ...mapState(['global_setting', "menus", 'application']),
        appList() {
            return (this.menus || []).filter(item => item.res_type === 'application');
        },
    },
    watch: {
        application() {
            this.init(this.application);
        },
    },
    mounted() {
        this.init();
    },
    methods: {
        async init(application) {
            const _this = this;
            await _this.initParamsList();
            _this.initTableOptions();
            _this.searchForm = $.extend({}, _this.searchForm, {
                application: application || _this.appList[0].code,
            });
            _this.getList(true);
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.type) !== -1);
            if (_this.type === 'field') {
                columns.forEach(item => {
                    if (item.prop !== 'auth_field_list') {
                        item.width = 150;
                    }
                });
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
            });
        },
        initParamsList() {
            const _this = this;
            if (_this.type !== 'field') {
                return;
            }
            return _this.fetchData(_this.$api.API_FindCommonParameterValuesByKey, {
                key1: 'data_field_auth',
            }).then(res => {
                _this.paramsList = res.data || [];
            }).catch(() => {
            });
        },
        handleHeaderEvent (event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        getList (init) {
            const _this = this;
            _this.dataList = [];
            if (init) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.type = _this.type;
            _this.fetchData(_this.$api.API_FindSysDataAuthConfigs, queryData).then(result => {
                _this.dataList = (result.data || []).map(item => {
                    let obj = $.extend({}, item);
                    obj.auth_field_list = [];
                    if (_this.$utils.isNotEmpty(item.auth_field)) {
                        obj.auth_field_list = JSON.parse(item.auth_field);
                    }
                    return obj;
                });
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent (event) {
            if (event.type === 'page') {
                this.getList();
            }
        },
        saveRow ({ row }) {
            const _this = this;
            _this.$set(row, 'auth_field', JSON.stringify(row.auth_field_list));
            let subData = $.extend({}, row);
            delete subData.auth_field_list;
            _this.fetchData(_this.$api.API_SaveSysDataAuthConfig, subData).then(() => {
                _this.$message.success('保存成功！');
            }).catch(() => {
            });
        },
    },
}
</script>

<style scoped>

</style>
